import 'package:flutter/cupertino.dart';
import 'package:flutter_li_ke_jie/core/http/http.dart';
import 'package:flutter_li_ke_jie/core/utils/toast.dart';
import 'package:flutter_li_ke_jie/entity/app_user.dart';
import 'package:flutter_li_ke_jie/utils/sputil.dart';

import '../../constant/api_constant.dart';
import '../../utils/log.dart';

class RealNameModel with ChangeNotifier{

  //保存用户信息
  Future<bool> saveUser(String name,String phone,String cardId) async{
    //校验
    RegExp expPhone =RegExp(r'1((3[0-9])|(4[5-7])|(4[0|9])|(5[0-3])|(5[5-9])|66|(7[5-8])|(7[2|3])|(8[0-9])|(9[5-9])|(9[1|3]))\d{8}$');
    bool matchedPhone = expPhone.hasMatch(phone);
    if(!matchedPhone){
      ToastUtils.error("手机号格式错误");
      return Future.value(false);
    }

    if(name==null||name.isEmpty){
      ToastUtils.error("请输入姓名");
      return Future.value(false);
    }

    // ignore: valid_regexps
    // RegExp expCardId =RegExp(r'^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|(^[1-9]\\d{5}\\d{2}(0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$');
    RegExp expCardId = RegExp(r'^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$');
    if(cardId==null||cardId.isEmpty||!expCardId.hasMatch(cardId)){
      ToastUtils.error("身份证格式错误");
      return Future.value(false);
    }
    //提交
    //获取用户信息
    AppUser? appUser = SPUtil.getUserInfo();
    appUser ??= AppUser();
    appUser.name = name;
    appUser.authPhone = phone;
    appUser.cardId = cardId;
    bool isSuccess = false;
    await XHttp.postJson(SAVE_USER_API,appUser.toJson()).then((response){
        Log.e("实名认证返回结果:$response");
        if(response!=null&&response["code"]==200){
          //更新实名认证状态
          SPUtil.saveAuthState("1");
          //更新用户信息
          SPUtil.saveUserInfo(appUser!);
          isSuccess = true;
        }else{
          ToastUtils.error(response["msg"]);
        }
    });
    return Future.value(isSuccess);
  }
}